<script setup lang="ts">
import type { CustomDialogInstance, EquipmentClassification } from '@/types'

import { BASE, PICTURE } from '@/views/equipment-definition/constant'

import ItemComponent from './item-component.vue'
import type { FormInstance } from 'element-plus'
import type { SaveParams } from '../type'
import { EQUIPMENT_COMPONENT_TYPE } from '@/enum'
import { cloneDeep } from 'lodash-es'

const props = defineProps<{
  pointId: number
  typeKey: string
  equipmentId?: number
  isViewing?: boolean
}>()
const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'saveSuccess'): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const formRef = ref<FormInstance>()
const equipmentStore = useEquipmentStore()

const tabId = ref(BASE)
const info = ref<EquipmentClassification[]>([])
const formData = ref<Record<string, any>>({})

const title = computed(() => {
  if (props.isViewing) {
    return '查看设备档案'
  }
  else if (props.equipmentId) {
    return '修改设备档案'
  }
  else {
    return '新增设备档案'
  }
})

// 组装表单数据
function assembleFormData(): SaveParams {
  const form = formData.value
  const getValueByKey: (key: string) => any = (key: string) => {
    let ret = null
    for (const item of info.value) {
      for (const subItem of item.list) {
        const _uuid = subItem._uuid
        const value = form[_uuid]
        if (subItem.parameter === key) {
          ret = value
        }
      }
    }
    return ret
  }

  function getList() {
    const infoValue = cloneDeep(info.value)

    for (const item of infoValue) {
      for (const subItem of item.list) {
        const _uuid = subItem._uuid
        const value = form[_uuid]
        if (typeof value === 'object') {
          subItem.attachments = value
        }
        else {
          subItem.value = value
        }

        // 新增时去掉id
        if (!props.equipmentId) {
          subItem.id = null
        }
      }
    }
    return infoValue
  }
  return {
    typeKey: props.typeKey,
    classificationVoList: getList(),
    equipmentInfo: {
      id: props.equipmentId ?? null,
      typeKey: props.typeKey,
      pointId: props.pointId,
      name: getValueByKey('name'),
      num: getValueByKey('num'),
      status: getValueByKey('status'),
      useStatus: getValueByKey('useStatus'),
      efficiencyLevel: getValueByKey('efficiencyLevel'),
      specification: getValueByKey('specification'),
      installationAddr: getValueByKey('installationAddr'),
      brand: getValueByKey('brand'),
      manufacturer: getValueByKey('manufacturer'),
      installationTime: getValueByKey('installationTime'),
      enableTime: getValueByKey('enableTime'),
      special: getValueByKey('special'),
      environmentalProtection: getValueByKey('environmentalProtection'),
      parent: getValueByKey('parent'),
    },
  }
}

async function clickConfirm(done: () => void) {
  const isValid = await formRef.value?.validate().catch(() => {
    done()
  })
  if (isValid) {
    const params = assembleFormData()
    // console.log(params)
    try {
      await equipmentDefinitionInfoApi.saveEquipmentInfo(params)
      done()
      close()
      ElMessage.success('保存成功')
      emit('saveSuccess')
    }
    finally {
      done()
    }
  }
  else {
    ElMessage.error('请完善信息')
  }
}

async function getInfo() {
  info.value = await equipmentStore.getDefinitions({
    typeKey: props.typeKey,
    equipmentId: props.equipmentId,
  })
  for (const item of info.value) {
    for (const subItem of item.list) {
      formData.value[subItem._uuid] = subItem.type === EQUIPMENT_COMPONENT_TYPE.ATTACHMENT
        ? subItem.attachments ?? []
        : subItem.value
    }
  }
}

async function open() {
  tabId.value = BASE
  await getInfo()
  dialogRef.value?.open()
  emit('open')
}
async function close() {
  dialogRef.value?.close()
  emit('close')
}

function onClose() {
  formData.value = {} as SaveParams
  formRef.value?.resetFields()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="title"
    width="740px"
    :show-confirm-button="!isViewing"
    @close="onClose"
    @confirm="clickConfirm"
  >
    <div class="h-100 w-full flex">
      <div class="flex-shrink-0">
        <ElTabs v-model="tabId" class="h-full" tab-position="left">
          <ElTabPane v-for="item in info" :key="item.key" :label="item.name" :name="item.key" />
        </ElTabs>
      </div>
      <div class="flex-auto overflow-auto">
        <ElForm ref="formRef" :disabled="isViewing" :model="formData" label-width="120px" class="py-3 pr-6">
          <template v-for="item in info" :key="item.key">
            <div v-show="item.key === tabId">
              <ItemComponent
                v-for="(subItem, index) in item.list"
                :key="`${item.key}_${index}`"
                v-model:obj="formData"
                :label="subItem.name"
                :prop="subItem._uuid"
                :disabled="isViewing"
                :is-picture="item.key === PICTURE"
                v-bind="subItem"
              />
            </div>
          </template>
        </ElForm>
      </div>
    </div>
  </CustomDialog>
</template>
